import Vue from 'vue'
import Router from 'vue-router'
import store from './store'
import { getToken } from '@/utils/auth' // get token from cookie
// 导入 NProgress 包对应的JS和CSS
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
// import Login from './components/Login.vue'
const Login = () =>
    import ( /* webpackChunkName: "login_home_welcome" */ './components/Login.vue')
    // import Home from './components/Home.vue'
const Home = () =>
    import ( /* webpackChunkName: "login_home_welcome" */ './components/Home.vue')
    // import Welcome from './components/Welcome.vue'
const Welcome = () =>
    import ( /* webpackChunkName: "login_home_welcome" */ './components/Welcome.vue')

// import Users from './components/user/Users.vue'
const Users = () =>
    import ( /* webpackChunkName: "Users_Rights_Roles" */ './components/user/Users.vue')


const wuhuDetails = () =>
    import ( /* webpackChunkName: "Order_Report" */ './components/table/wuhuDetails.vue')
const townDownList = () =>
    import ( /* webpackChunkName: "Order_Report" */ './components/tree/townDownList.vue')
const allInfoList = () =>
    import ( /* webpackChunkName: "Order_Report" */ './components/tree/allInfoList.vue')
const demoTable4 = () =>
    import ( /* webpackChunkName: "Order_Report" */ './components/tree/demo4.vue')
const equMapDetails = () =>
    import ( /* webpackChunkName: "Order_Report" */ './components/tree/equMapDetails.vue')
const camList = () =>
    import ( /* webpackChunkName: "Order_Report" */ './components/tree/cameraList.vue')
const defenMapDetail = () =>
    import ( /* webpackChunkName: "Order_Report" */ './components/tree/defenMapDetails.vue')
Vue.use(Router)


const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
const router = new Router({
    routes: [
        { path: '/', redirect: '/login' },
        { path: '/login', component: Login },
        {
            path: '/home',
            component: Home,
            redirect: '/welcome',
            children: [
                { path: '/wuhu', component: wuhuDetails },
                { path: '/demo', component: townDownList },
                { path: '/all', component: allInfoList },
                { path: '/demo4', component: demoTable4 },
                { path: '/equmap/:id', component: equMapDetails },
                { path: '/camli', component: camList },
                { path: '/defenmap', component: defenMapDetail },
            ]
        }
    ]
})

// 挂载路由导航守卫
router.beforeEach(async(to, from, next) => {
    console.log("route.beforeEach :to" + to + "from:" + from + "next:");
    // console.log(to);
    // console.log(from);
    // start progress bar
    NProgress.start()

    if (to.path.startsWith('/cu/local') || to.path.startsWith('/cu/') || to.path.startsWith('/main/')) {
        next()
        return
    }
    // set page title
    // document.title = getPageTitle(to.meta.title)

    // determine whether the user has logged in
    const hasToken = getToken()

    // console.log("hasToken:" + hasToken);
    // 如果存在token
    if (hasToken) {
        // 去登录页直接去
        if (to.path === '/login') {
            // if is logged in, redirect to the home page
            next({ path: '/' })
            NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
        } else {
            // determine whether the user has obtained his permission roles through getInfo
            // 不是去登录页需要判断用户权限
            const hasRoles = store.getters.roles && store.getters.roles.length > 0
                // if (hasRoles) {
            if (true) {
                next()
            } else {
                try {
                    // get user info
                    // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
                    const { roles } = await store.dispatch('user/getInfo')
                        // var { roles } = await this.$http.get('/api/auth/v1/user/info', 'hasToken')
                    console.log("res:" + roles);
                    console.log("到这里了:");
                    // TODO: 根据用户权限设置路由
                    // generate accessible routes map based on roles
                    // 根据角色生成可以访问的路由
                    const accessRoutes = await store.dispatch(
                        'permission/generateRoutes',
                        roles
                    )
                    console.log("到这里了:" + accessRoutes);
                    // dynamically add accessible routes
                    router.addRoutes(accessRoutes)
                        // hack method to ensure that addRoutes is complete
                        // set the replace: true, so the navigation will not leave a history record
                    next({...to, replace: true })
                } catch (error) {
                    // remove token and go to login page to re-login
                    await store.dispatch('user/resetToken')
                    Message.error(error || 'Has Error')
                    next(`/login?redirect=${to.path}`)
                    NProgress.done()
                }
            }
        }
    } else {
        /* has no token*/

        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            next()
        } else {
            // other pages that do not have permission to access are redirected to the login page.
            next(`/login?redirect=${to.path}`)
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
})

export default router